import { reactive, watch, ref } from 'vue'
import type { Ref } from 'vue'

import { removeUndefinedParams } from '@/utils/index'
import type { BasicPagingListParams } from '@/apis/basicModel'
import { getFactorList } from '@/apis/system/config/factorList'
import type { SearchOptionsType, CPageTableProps } from '@/components/CPageTable'
import { ColumnSettingTypeEnum } from '@/components/CPageTable'

import { UnconfirmedRuleEnum } from '@/constants/system'
import { getUnconfirmedRuleList } from '@/apis/system/config/factorMatchingRule'

export const useList = (tableRef: Ref) => {
  const searchForm = reactive({
    // 规则处理状态
    status: UnconfirmedRuleEnum.WAIT_CONFIRM,
    // 关联次数
    relationNumGreater: undefined,
    // 流类型
    flowType: undefined,
    // 流名称
    flowName: undefined
  })
  function loadData(parameter: BasicPagingListParams) {
    const params = Object.assign(handleParams(), parameter)
    return getUnconfirmedRuleList(params)
  }

  // 处理参数
  const handleParams = () => {
    // 参数
    let params = {
      flowName: searchForm?.flowName,
      flowType: searchForm?.flowType,
      relationNumGreater: searchForm?.relationNumGreater || undefined,
      status: searchForm.status
      // status: 'ENABLE'
    }
    params = removeUndefinedParams(params)
    return params
  }
  watch(searchForm, () => {
    tableRef.value?.refresh(true)
  })

  const tableFieldsSetting: CPageTableProps['tableFieldsSetting'] = [
    {
      title: '流类型',
      field: 'flowType',
      slot: 'flowType',
      width: '150',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '流名称',
      field: 'flowName',
      minWidth: '150',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '核算标准',
      field: 'accountStandard',
      slot: 'accountStandard',
      minWidth: '150',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '规则类型',
      field: 'ruleCategory',
      slot: 'ruleCategory',
      minWidth: '150',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '关联因子',
      field: 'factorNo',
      slot: 'factorNo',
      minWidth: '200',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '关联次数',
      field: 'relationNum',
      minWidth: '80',
      columnSettingConfig: {
        enabled: true
      }
    },
    {
      title: '操作',
      field: 'op',
      slot: 'op',
      width: 180,
      fixed: 'right',
      columnSettingConfig: {
        enabled: true,
        type: ColumnSettingTypeEnum.FIXED
      }
    }
  ]
  return {
    tableFieldsSetting,
    searchForm,
    loadData,
    tableRef
  }
}
